package com.sgb.kjwl.view.ui.fragment.home;

import android.content.Context;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentLease2Binding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.swgk.core.view.entity.MenuEntity;
import com.sgb.kjwl.model.entity.ShowCarEntity;
import com.sgb.kjwl.model.entity.ShowDeviceEntity;
import com.sgb.kjwl.model.entity.ShowMachineEntity;
import com.sgb.kjwl.view.event.ChooseAreaEvent;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.device.DeviceDetailActivity;
import com.sgb.kjwl.view.ui.activity.device.DeviceListActivity3;
import com.sgb.kjwl.view.ui.activity.leaseAsk.CarListActivity3;
import com.sgb.kjwl.view.ui.activity.leaseAsk.MachineListActivity3;
import com.sgb.kjwl.view.ui.activity.leaseAsk.MachineOutActivity;
import com.sgb.kjwl.view.ui.adapter.home.ShowCarAdapter;
import com.sgb.kjwl.view.ui.adapter.home.ShowDeviceAdapter;
import com.sgb.kjwl.view.ui.adapter.home.ShowMechanicsAdapter;
import com.sgb.kjwl.viewmodel.home.LeaseFragment2Model;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.adapter.FragPagerAdapter;
import com.swgk.core.refresh.SuperSwipeRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;


/**
 * Description:
 * Author cfk
 * Time
 * 船🚢新版本租凭fragment
 */
//TODO 暂时备份之前homefragment内容
@Deprecated
public class LeaseFragment2 extends AppFragment {
    public static final int MACHINE = 0;
    public static final int DEVICE = 1;
    public static final int LEASE_FRAGMENT = 100;
    public static final String KEY_TYPE = "type";
    private int page;
    public static final int COLUMN_COUNT = 4;
    public static final int ROW_COUNT = 1;
    private FragmentLease2Binding binding;
    private String type = "";
    private MainActivity activity;
    private FragPagerAdapter menuAdapter;
    private ArrayList<Fragment> menuFragments;
    private ImageView[] memuTip;
    private boolean isCreate = false;
    private boolean init = true;
    private boolean isVisible;
    private ShowMechanicsAdapter showMechanicsAdapter;
    private ShowDeviceAdapter showDeviceAdapter;
    private ShowCarAdapter showCarAdapter;
    @Inject
    LeaseFragment2Model viewModel;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof MainActivity) {
            activity = (MainActivity) context;
        }
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    public static LeaseFragment2 newInstance(String type) {
        LeaseFragment2 fragment = new LeaseFragment2();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (!isCreate) {
            return;
        }
        if (isVisibleToUser) {
            if (init) {
                init = false;
                init();
            }
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isCreate = true;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_lease2, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        type = (String) getArguments().get(KEY_TYPE);
        initView();
        if (init && isVisible) {
            init = false;
            init();
        }
    }

    private void initView() {
        binding.llMore.setOnClickListener(this);
        binding.llMore1.setOnClickListener(this);
        binding.llMore2.setOnClickListener(this);
        //首页推荐机械
        if (showMechanicsAdapter == null) {
            showMechanicsAdapter = new ShowMechanicsAdapter(getActivity(), null);
        }
        showMechanicsAdapter.setOnItemClick(new AdapterOnItemClick<ShowMachineEntity>() {
            @Override
            public void onItemClick(ShowMachineEntity showMachineEntity, int position) {
                MachineOutActivity.start(getActivity(), showMachineEntity.getId());
            }
        });

        binding.rlvOption.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        binding.rlvOption.setAdapter(showMechanicsAdapter);
        binding.rlvOption.setHasFixedSize(false);

        //首页 推荐设备
        if (showDeviceAdapter == null) {
            showDeviceAdapter = new ShowDeviceAdapter(getActivity(), null);
        }
        showDeviceAdapter.setOnItemClick(new AdapterOnItemClick<ShowDeviceEntity>() {
            @Override
            public void onItemClick(ShowDeviceEntity showDeviceEntity, int position) {
                DeviceDetailActivity.start(getActivity(), showDeviceEntity.getId());
            }
        });
        binding.rlvOption1.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        binding.rlvOption1.setAdapter(showDeviceAdapter);
        binding.rlvOption1.setHasFixedSize(false);

        //首页 推荐车辆
        if (showCarAdapter == null) {
            showCarAdapter = new ShowCarAdapter(getActivity(), null);
        }
        showCarAdapter.setOnItemClick(new AdapterOnItemClick<ShowCarEntity>() {
            @Override
            public void onItemClick(ShowCarEntity showCarEntity, int position) {
                viewModel.getH5Url(showCarEntity.getId());
            }
        });
        binding.rlvOption2.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        binding.rlvOption2.setAdapter(showCarAdapter);
        binding.rlvOption2.setHasFixedSize(false);
        binding.swipeRefresh.setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {
            @Override
            public void onRefresh() {
                textView.setText("正在刷新");
                viewModel.getMenu();
                viewModel.getShowMechanics();
                viewModel.getShowDevice();
                viewModel.getShowCar();
            }

            @Override
            public void onPullDistance(int distance) {

            }

            @Override
            public void onPullEnable(boolean enable) {
                textView.setText(enable ? "释放立即刷新" : "下拉刷新");
            }
        });
        binding.swipeRefresh.setHeaderView(createHeaderView());
    }

    private void init() {
        viewModel.getMenu();
        viewModel.getShowMechanics();
        viewModel.getShowDevice();
        viewModel.getShowCar();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_more:
                MachineListActivity3.start(getActivity());
                break;
            case R.id.ll_more1:
                DeviceListActivity3.start(getActivity());
                break;
            case R.id.ll_more2:
                CarListActivity3.start(getActivity());
                break;
        }
    }

    private ProgressBar progressBar;
    private TextView textView;

    private View createHeaderView() {
        View headerView = LayoutInflater.from(binding.swipeRefresh.getContext())
                .inflate(R.layout.super_swipe_refresh_head, null);
        progressBar = headerView.findViewById(R.id.pb_view);
        textView = headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        progressBar.setVisibility(View.GONE);
        return headerView;
    }

    public void showMenuView(List<MenuEntity> data) {
        binding.swipeRefresh.setRefreshing(false);
        menuFragments = new ArrayList<>();
        int total = data.size();
        page = total % (COLUMN_COUNT * ROW_COUNT) > 0 ? total / (COLUMN_COUNT * ROW_COUNT) + 1 : total / (COLUMN_COUNT * ROW_COUNT);
        for (int i = 0; i < page; i++) {
            List<MenuEntity> menuEntityList = new ArrayList<>();
            int fir = i * COLUMN_COUNT * ROW_COUNT;
            int last = (i + 1) * COLUMN_COUNT * ROW_COUNT > total ? total : (i + 1) * COLUMN_COUNT * ROW_COUNT;
            menuEntityList.addAll(data.subList(fir, last));
            menuFragments.add(LeaseMenuFragment.newInstance(menuEntityList, COLUMN_COUNT, ROW_COUNT, LEASE_FRAGMENT));
        }
        menuAdapter = new FragPagerAdapter(getChildFragmentManager(), menuFragments);
        binding.viewpager.setAdapter(menuAdapter);
        binding.viewpager.setOffscreenPageLimit(page);
        binding.viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setImageBackgroundMenu(position % page);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        initDotsMenu();
        binding.viewpager.setCurrentItem(0);
    }

    private void setImageBackgroundMenu(int selectItems) {
        for (int i = 0; i < memuTip.length; i++) {
            if (i == selectItems) {
                memuTip[i].setSelected(true);
            } else {
                memuTip[i].setSelected(false);
            }
        }
    }


    private void initDotsMenu() {
        binding.dotMenuLayout.removeAllViews();
        memuTip = new ImageView[page];
        for (int i = 0; i < page; i++) {
            ImageView imageView = new ImageView(this.getActivity());
            imageView.setBackgroundResource(R.drawable.select_banner_dot);
            memuTip[i] = imageView;
            if (i == 0) {
                memuTip[i].setSelected(true);
            } else {
                memuTip[i].setSelected(false);
            }
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams((int) getResources().getDimension(R.dimen.dp8),
                    (int) getResources().getDimension(R.dimen.dp8)));
            layoutParams.leftMargin = (int) getResources().getDimension(R.dimen.dp5);
            layoutParams.rightMargin = (int) getResources().getDimension(R.dimen.dp5);
            binding.dotMenuLayout.addView(imageView, layoutParams);
        }
    }

    public void showOptionView(List<ShowMachineEntity> datas) {
        binding.swipeRefresh.setRefreshing(false);
        if (datas.isEmpty()) {
            binding.ntscrollView.setVisibility(View.VISIBLE);
            binding.empty.setVisibility(View.VISIBLE);
            binding.rlvOption.setVisibility(View.GONE);
        } else {
            binding.ntscrollView.setVisibility(View.GONE);
            binding.empty.setVisibility(View.GONE);
            binding.rlvOption.setVisibility(View.VISIBLE);
            showMechanicsAdapter.setDatas(datas);
        }
    }

    public void showOptionView1(List<ShowDeviceEntity> datas) {
        binding.swipeRefresh.setRefreshing(false);
        if (datas.isEmpty()) {
            binding.ntscrollView1.setVisibility(View.VISIBLE);
            binding.empty1.setVisibility(View.VISIBLE);
            binding.rlvOption1.setVisibility(View.GONE);
        } else {
            binding.ntscrollView1.setVisibility(View.GONE);
            binding.empty1.setVisibility(View.GONE);
            binding.rlvOption1.setVisibility(View.VISIBLE);
            showDeviceAdapter.setDatas(datas);
        }
    }

    public void showOptionView2(List<ShowCarEntity> datas) {
        binding.swipeRefresh.setRefreshing(false);
        if (datas.isEmpty()) {
            binding.ntscrollView2.setVisibility(View.VISIBLE);
            binding.empty2.setVisibility(View.VISIBLE);
            binding.rlvOption2.setVisibility(View.GONE);
        } else {
            binding.ntscrollView2.setVisibility(View.GONE);
            binding.empty2.setVisibility(View.GONE);
            binding.rlvOption2.setVisibility(View.VISIBLE);
            showCarAdapter.setDatas(datas);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(ChooseAreaEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CHOOSE_AERA) {
            viewModel.getShowMechanics();
            viewModel.getShowDevice();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
